import {
  inject,
  type InjectionKey,
  provide,
  reactive,
  readonly as defineReadonly
} from 'vue';

export interface CreateContextOptions {
  readonly?: boolean;
  native?: boolean;
}

/**
 * @description 局部 context
 * @author wfd
 * @date 2022/11/3 08:49
 * @example
 * @param context
 * @param {InjectionKey<T>} key
 * @param {CreateContextOptions} options
 * @returns {any}
 */
export function createContext<T> (context: any, key: InjectionKey<T> = Symbol(),
  options: CreateContextOptions = {}) {
  const { readonly = false, native = true } = options;
  const state = reactive(context);
  const provideData = readonly ? defineReadonly(state) : state;
  provide(key, native ? context : provideData);
  
  return {
    state
  };
}

export function useContext<T> (key: InjectionKey<T> = Symbol(),
  defaultValue?: any) {
  return inject(key, defaultValue || {});
}
